package com.wondertek.poms.core.filter.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import com.wondertek.poms.core.filter.BaseRuleFilter;
import com.wondertek.poms.core.filter.RuleFilterChain;
import org.apache.commons.lang3.StringUtils;

import com.wondertek.poms.dao.po.Content;
import com.wondertek.poms.dao.po.DefaultPrdSal;
import com.wondertek.poms.dao.po.IRulePo;
import com.wondertek.poms.dao.po.PrdInfoRule;
import com.wondertek.poms.dao.po.PrdRuleSecondClassify;
import com.wondertek.poms.dao.po.SecondClassify;


import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * <p><b>SecondClassifyFilter Description:</b> 二级分类过滤器</p>
 * @author douzi
 * <b>DATE</b> 2020年11月16日 下午4:50:10
 */
@Slf4j
public class SecondClassifyFilter extends BaseRuleFilter {

	@Override
	public void doFilter(IRulePo rule, Content c, RuleFilterChain chain) {
		if (rule instanceof PrdInfoRule) {
			PrdInfoRule r = (PrdInfoRule) rule;
			this.process(r.getPrdRuleId(),
					r.getSecondClassifys(),
					c.getSecondClassifyList(),
					chain,
					"二级分类-SecondClassifyList", c);
		} else if (rule instanceof DefaultPrdSal) {
			DefaultPrdSal r = (DefaultPrdSal) rule;
			this.process(r.getId(),
					r.getSecondClass(),
					c.getSecondClassifyList(),
					chain,
					"二级分类-SecondClassifyList", c);
		}

		chain.doFilter(rule, c, chain);
	}
	
	/**
	 * <p><b>Title:</b> process</p>
	 * <p><b>Description:</b> DefaultPrdSal 默认计费过滤方法</p>
	 * @author douzi
	 * @param prdRuleId
	 * @param ruleSecondClass
	 * @param secondClassifyList
	 * @param chain
	 * @param comments
	 * @param c
	 */
	private void process(Long prdRuleId, String ruleSecondClass,
			List<SecondClassify> secondClassifyList, RuleFilterChain chain, String comments, Content c) {
		if (chain.isFlag() && StringUtils.isNotBlank(ruleSecondClass)) {
			chain.setFlag(filterSClassify(prdRuleId, ruleSecondClass, secondClassifyList));
            log(prdRuleId, chain, comments,  ruleSecondClass, JSONUtil.toJsonStr(secondClassifyList));
        }
	}
	private boolean filterSClassify(Long prdRuleId, String ruleSecondClass, List<SecondClassify> scList) {
		boolean flag = false;
		Map<String, List<String>> ruleMap = new HashMap<String, List<String>>();
		ruleSecondClass = ruleSecondClass.replaceAll("：", ":").replaceAll("；", ";").replaceAll("，", ",");
		boolean isRight = true;
		if (ruleSecondClass != null && !ruleSecondClass.equals("")) {
			for (String singleClassTag : ruleSecondClass.split(";")) {
				String[] keyValue = singleClassTag.split(":");
				if (keyValue != null && keyValue.length == 2) {
					String key = keyValue[0].trim();
					List<String> valueList = new LinkedList<String>();
					if (key.length() > 0) {
						for (String value : keyValue[1].trim().split(",")) {
							if (value.trim().length() > 0) {
								valueList.add(value.trim());
							}
						}
						if (valueList.size() > 0) {
							ruleMap.put(key, valueList);
						}
					}
				}
				if(keyValue.length != 2){
					isRight = false;
					log.error("==二级分类配置错误 规则id: " + prdRuleId + "==");
					break;
				}
			}
		}
		if(isRight) {
			if(scList != null && scList.size() > 0) {
				Map<String, List<String>> secMap = new HashMap<String, List<String>>();
				for (SecondClassify sec : scList) {
					String[] values = sec.getClassifyValue().split("\\|");
					List<String> valueList = secMap.get(sec.getClassifyKey());
					if (valueList == null) {
						valueList = new LinkedList<String>();
					}
					valueList.addAll(Arrays.asList(values));
					secMap.put(sec.getClassifyKey(), valueList);
				}
				
				//开始匹配
				Iterator<Entry<String, List<String>>> iter = ruleMap.entrySet().iterator();
				boolean isIn = true;
				while (iter.hasNext()) {
					Entry<String, List<String>> entry = (Entry<String, List<String>>) iter.next();
					String ruleKey = (String)entry.getKey();
					List<String> ruleVal = (List<String>)entry.getValue();
					
					if(!secMap.containsKey(ruleKey) || !secMap.get(ruleKey).containsAll(ruleVal)) {
						isIn = false;
					}
				}
				if(isIn) {
					flag = true;
				}
			}
		}
		return flag;
	}

	/**
	 * <p><b>Title:</b> process</p>
	 * <p><b>Description:</b> PrdInfoRule 已选、限制规则过滤方法</p>
	 * @author douzi
	 * @param prdRuleId
	 * @param secondClassifys
	 * @param secondClassifyList
	 * @param chain
	 * @param comments
	 * @param c
	 */
	private void process(Long prdRuleId, Set<PrdRuleSecondClassify> secondClassifys,
			List<SecondClassify> secondClassifyList, RuleFilterChain chain, String comments, Content c) {
		if (chain.isFlag() && secondClassifys.size() > 0) {
			chain.setFlag(filterSClassify(secondClassifys, secondClassifyList));
            log(prdRuleId, chain, comments,  JSONUtil.toJsonStr(secondClassifys), JSONUtil.toJsonStr(secondClassifyList));
        }
	}

	public static void main(String[] args) {
		Set<PrdRuleSecondClassify> secondClassifys = new HashSet<>();
		PrdRuleSecondClassify prsc = new PrdRuleSecondClassify();
		prsc.setId(1l);
		prsc.setKey("内容形态");
		prsc.setPrdRuleId(1l);
		prsc.setValues("全片1,精编");
		prsc.setType("1");
		secondClassifys.add(prsc);
		
		PrdRuleSecondClassify prsc1 = new PrdRuleSecondClassify();
		prsc1.setId(1l);
		prsc1.setKey("电视台");
		prsc1.setPrdRuleId(1l);
		prsc1.setValues("台湾台,浙江台");
		prsc1.setType("1");
		secondClassifys.add(prsc1);
		
		List<SecondClassify> secondClassifyList = new ArrayList<>();
		SecondClassify sc = new SecondClassify();
		sc.setClassifyKey("内容形态");
		sc.setClassifyValue("全片");
		sc.setId(1l);
		sc.setContentId("213454667");
		secondClassifyList.add(sc);
		
		SecondClassify sc1 = new SecondClassify();
		sc1.setClassifyKey("电视台");
		sc1.setClassifyValue("浙江台");
		sc1.setId(1l);
		sc1.setContentId("213454667");
		secondClassifyList.add(sc1);
		
		System.out.println(filterSClassify(secondClassifys, secondClassifyList));
	}
	
	/**
	 * <p><b>Title:</b> filterSClassify</p>
	 * <p><b>Description:</b> 直接设置</p>
	 * @author douzi
	 * @param secondClassifys
	 * @param secondClassifyList
	 */
	private static boolean filterSClassify(Set<PrdRuleSecondClassify> secondClassifys,
			List<SecondClassify> secondClassifyList) {
		boolean flag = true;
		if (secondClassifyList != null && secondClassifyList.size() > 0) {
			boolean isIncludeMatch = false;
			boolean isExcludeMatch = false;
			Iterator<PrdRuleSecondClassify> it = secondClassifys.iterator();
			while (it.hasNext()) {
				PrdRuleSecondClassify ruleSc = it.next();
				if (ruleSc.getType().equals("1")) {// 筛选二级分类
					boolean isMatch = false;
					for (SecondClassify sc : secondClassifyList) {// 同一个key可能有多条记录
						if (ruleSc.getKey().equals(sc.getClassifyKey())) {
							String values = "," + ruleSc.getValues() + ",";
							String cv = "," + sc.getClassifyValue() + ",";
							if (values.indexOf(cv) > -1) {// "a,b"包含"b"
								isMatch = true;
							}
						}
					}
					isIncludeMatch = isMatch;
					if (!isMatch) {// 规则中一个不匹配即为不匹配
						flag = false;
						break;
					}
				} else if (ruleSc.getType().equals("0")) {// 排除二级分类
					boolean isMatch = false;
					for (SecondClassify sc : secondClassifyList) {// 同一个key可能有多条记录
						if (ruleSc.getKey().equals(sc.getClassifyKey())) {
							String values = "," + ruleSc.getValues() + ",";
							String cv = "," + sc.getClassifyValue() + ",";
							if (values.indexOf(cv) > -1) {// "a,b"包含"b"
								isMatch = true;
							}
						}
					}
					isExcludeMatch = isMatch;
					if (isMatch) {// 排除条件只要满足一个，即为排除
						flag = false;
						break;
					}
				}
			}

			if (isIncludeMatch && !isExcludeMatch) {// 筛选规则都满足并且排除规则都不满足
				flag = true;
			}
		} else {
			flag = secondClassifyList.size() == 0;
		}
		return flag;
	}

}
